
#include <QtCore/QDir>
#include <QtCore/QStringList>
#include <QtGui/QColor>

#include "imageLoader.h"

/*----------------------------------------------------------------------------*/


ImageLoader::ImageLoader()
{
}

/*----------------------------------------------------------------------------*/


ImageLoader::~ImageLoader()
{
	for ( size_t i = 0; i < m_imageArray.size(); i++ )
	{
		if ( m_imageArray[i] )		
			delete m_imageArray[i];		
	}
}


/*----------------------------------------------------------------------------*/


void ImageLoader::LoadBmpFilesToImages( const QString& _trainFilesDir )
{
	for ( size_t i = 0; i < m_imageArray.size(); i++ )
	{
		if( m_imageArray[i] )
			delete m_imageArray[i];
	}
	m_imageArray.resize( 0 );

	QStringList filesList = BrowseFiles( _trainFilesDir );
	for ( int i = 0; i < filesList.size(); i++ )
	{			
		m_imageArray.push_back( CreateImageFromBmp( filesList[i] ) );
		/** temp */
		//m_imageArray[i]->PrintData();
	}
}


/*----------------------------------------------------------------------------*/


QStringList ImageLoader::BrowseFiles( const QString& _trainFilesDir )
{
	QDir currentDir = QDir::current();
	if ( !currentDir.cd( _trainFilesDir ) )
		throw "Directory not found!";
	
	currentDir.setNameFilters( QStringList( "*.bmp" ) );
	QStringList files = currentDir.entryList();
	for ( int i = 0; i < files.size(); i++ )
	{
		files[i] = currentDir.absoluteFilePath( files[i] );
	}

	return files;
}


/*----------------------------------------------------------------------------*/


CImage* ImageLoader::CreateImageFromBmp( QString& _fileName )
{
	QImage bmp( _fileName );
	//* 'A' ascii symbol has value '65', so if we get 'A' symbol, */
	//* active output is: 65 - 65 = 0, and so on   */
	int activeOutput = _fileName.section( '/', -1 )[0].toAscii() - 65;	

	return CreateImageFromBmp( bmp, activeOutput );
}


/*----------------------------------------------------------------------------*/


CImage* ImageLoader::CreateImageFromBmp( QImage& _image, int _activeOutput )
{
	DoubleV data;
	for ( int i = 0; i < _image.height(); i++ )
	{
		for ( int j = 0; j < _image.width(); j++ )
		{
			QColor pixelColor( _image.pixel( j, i ) );
			if ( ( pixelColor.red() <= 50 ) && ( pixelColor.green() <= 50 ) && ( pixelColor.blue() <= 50 ) )			
				data.push_back( 1.0 );
			else
				data.push_back( 0.0 );
		}
	}	
	/**!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!LOOK HERE!!!!!!!!!!!!!!!!!!!!!!!!!!!*/
	return new CImage( data, 3, _activeOutput );
}


/*----------------------------------------------------------------------------*/


ImageV& ImageLoader::GetImages()
{
	return m_imageArray;
}


/*----------------------------------------------------------------------------*/

